let CryptoJS = require('js-sha256').sha256;
import axios from 'axios';
import router from '../../src/router';
import {Toast, MessageBox} from 'mint-ui'

axios.defaults.timeout = 5000; //响应时间
// 允许携带cookie
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; //配置请求头
var debug = true;
if (debug) {
    axios.defaults.baseURL = 'https://www.fastmock.site'
    // axios.defaults.baseURL = 'https://test1.instore.cn/';
} else {
    axios.defaults.baseURL = 'https://api.tanxiaji.com/';
}
axios.interceptors.request.use(
    // element ui Loading方法
    function (config) {
        if (config.method == 'post') {
            config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
        }
        console.log('config--',config)
        let token = localStorage.getItem("token");
        let date = new Date();
        let year = date.getFullYear(); //获取当前年份
        let mon = date.getMonth() + 1; //获取当前月份
        let day = date.getDate();//获取当前日
        let h = date.getHours(); //获取小时
        let m = date.getMinutes(); //获取分钟
        let t3 = year + '' + p(mon) + '' + p(day) + '' + p(h) + '' + p(m);

        function p(s) {
            return s < 10 ? '0' + s : s;
        }

        token = '54onx5uhe3s7tvz50av4kr2dwvdwgwlj'
        let signature = CryptoJS(token + t3).toUpperCase();
        console.log("signature随机字符串--", signature);
        // console.log("时间", t3);
        // console.log("签名", signature);
        if (token) {
            config.headers.common['WEBMARK'] = token;
            config.headers.common['SIGN'] = signature;
        }
        return config
    },
    function (error) {
        return Promise.reject(error)
    }
)
//全局拦截
axios.interceptors.response.use(response => {
    console.log("http状态码，headers头", response.headers);
    if (response.data.errno == 201103 || response.data.errno == 201104) {
        MessageBox.alert('登录失效', '提示', {
            confirmButtonText: '确定',
            callback: action => {
                router.replace({
                    name: 'login',
                    query: {redirect: router.currentRoute.fullPath} //登录后再跳回此页面时要做的配置
                })
            }
        });
    }
    return response;
}, error => {
    if (error.response.status === 200) {
        Toast(error.response.data.errMsg)
    }
    if (error.response.status === 500) {
        Toast("服务器错误,请刷新再试")
        // router.push({
        //     path:'/login',
        //     query: {redirect: router.history.current.fullPath}
        // })
    }
    return Promise.resolve(error.response);
})

export default axios
